import promise from "es6-promise";
// import fetch from 'isomorphic-fetch';
import API from "src/utils/api";
import notification from "src/utils/notification";

import routes from "src/routers/router";
import VueRouter from "vue-router";
const router = new VueRouter({ routes });
import store from "src/utils/storage";
import { clearLoginInfo } from "src/utils/tools";

const ticket = GetQueryString("ticket");

function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

promise.polyfill();

function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

/**
 * options:{
 *    commit:action中的commit用于操作mutactions
 *    ,url:请求地址
 *    ,type:请求方式
 *    ,data:请求数据
 *     ,success:成功回调
 *     ,error:失败回调
 *     ,noWarningAlert:是否展示错误提示框 false 要展示,true 不展示
 *     ,isExport:false 是否是导出操作
 * }
 */
function fetch(options) {
  //全局loding
  options.commit && options.showLoading && options.commit("LOADING");
  //表格-区域loding
  options.commit && options.showRegionLoading && options.commit("REGION_LOADING");

  // 创建ajax对象
  var xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }

  if (options.isExport) {
    xhr.responseType = "blob";
  }
  xhr.withCredentials = true;

  // 请求方式
  options.type = options.type || "post";
  var type = options.type.toUpperCase();
  // 用于清除缓存
  var random = Math.random();

  // 添加公共请求参数
  let data = options.data || {};

  // 请求地址
  let reqUrl = API.DOMAIN + API.CONTEXT + options.url;
  if (reqUrl.indexOf("config/getProductCode") != -1) {
    reqUrl = reqUrl + `?ticket=${ticket}`;
  }
  // window.reqUrl = options.url;

  // 去除字符中的空白字符
  for (var key in data) {
    if (data[key] && Object.prototype.toString.call(data[key]) == "[object String]") {
      data[key] = data[key].replace(/(^\s*)|(\s*$)/g, "");
    }
  }

  if (type == "GET") {
    if (typeof data == "object") {
      var str = "";
      for (var key in data) {
        str += key + "=" + data[key] + "&";
      }
      data = str.replace(/&$/, "");
    }
    if (data) {
      xhr.open("GET", reqUrl + "?" + data, true);
    } else {
      xhr.open("GET", reqUrl + "?t=" + random, true);
    }

    xhr.send();
  } else if (type == "POST") {
    //去掉空值和未定义的值
    Object.keys(data).map(item => {
      if (data[item] === "" || data[item] == undefined) {
        delete data[item];
      }
    });

    xhr.open("POST", reqUrl, true);
    // 如果需要像 html 表单那样 POST 数据，请使用 setRequestHeader() 来添加 http 头。
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.send(JSON.stringify(data));
  }

  // 部分浏览器不支持timeout设置
  // if( navigator.userAgent.indexOf('Trident') === -1){
  //   xhr.timeout = 10*60 * 1000;
  // }

  xhr.ontimeout = function() {
    options.commit && options.showLoading && options.commit("UNLOADING");
    options.commit && options.showRegionLoading && options.commit("UN_REGION_LOADING");
    !options.noWarningAlert && notification.warning("请求超时");
  };

  // 处理返回数据
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if (options.isExport) {
          //如果是文件导出
          var fileReader = new FileReader();
          // 返回内容有时是出错信息,不是文件流信息,所以要判断一下
          fileReader.readAsText(new Blob([xhr.response]));
          fileReader.onload = function() {
            var result = fileReader.result;
            try {
              //如果出错,即返回json的错误数据类型
              var resultJSON = JSON.parse(result);
              if (resultJSON.returnCode != "000000") {
                options.error ? options.error(resultJSON) : notification.warning(resultJSON.returnMsg);
              }
            } catch (e) {
              //没有返回json数据则执行下载回调
              // console.log(e);
              options.success && options.success(xhr.response);
            }
          };
        } else {
          resHandler(xhr.responseText, options);
        }
      } else {
        errorHandler(options.commit, options.showLoading, options.showRegionLoading, xhr, options.noWarningAlert);
      }
    }
  };
}

//捕捉浏览器返回的状态码
function checkStatus(response, noWarningAlert) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  var msg = "";
  switch (response.status.toString()) {
    case "0":
      msg = "您的网络有问题,请稍后再试。";
      break;
    case "302":
      msg = "临时重定向";
      break;
    case "403":
      msg = "无访问权限";
      break;
    case "404":
      msg = "请求的资源不存在";
      break;
    case "500":
    case "501":
    case "502":
    case "504":
      msg = "服务器内部错误";
      break;
    default:
      msg = "未知错误";
  }
  !noWarningAlert && notification.error(msg);
  return Promise.reject({ msg: msg });
}

// 标记是否第一次弹出登录超时窗口
var isFirstTimeout = true;

// 请求成功处理
function resHandler(resData, options) {
  // 隐藏加载动画
  options.commit && options.showLoading && options.commit("UNLOADING");
  options.commit && options.showRegionLoading && options.commit("UN_REGION_LOADING");

  // isFlag = false;
  // 将字符串json数据转化成json对象

  // if(window.reqUrl == '/config/export'){
  //     return;
  // }

  // JSON.parse(resData)对应key为数字的类型会报错
  resData = resData && typeof resData != "object" ? eval("(" + resData + ")") : resData;

  if (resData) {
    if (resData.status && resData.status != 200) {
      return errorHandler(options.commit, options.showLoading, options.showRegionLoading, resData.error, options.noWarningAlert);
    }
    if (resData.returnCode == "000000") {
      options.success && options.success(resData.returnData || {});
    } // 内外部登录超时
    else if (resData.returnCode == "100010") {
      notification.warning(resData.returnMsg);
      setTimeout(() => {
        clearLoginInfo();
      }, 1000);
    } else {
      if (options.error) {
        options.error(resData);
      } else {
        !options.noWarningAlert && notification.warning(resData.returnMsg);
      }
    }
  }
}

// 异常处理
function errorHandler(commit, showLoading, showRegionLoading, xhr, noWarningAlert) {
  // isFlag = false;
  // 隐藏加载动画
  checkStatus(xhr, noWarningAlert);
  commit && showLoading && commit("UNLOADING");
  commit && showRegionLoading && commit("UN_REGION_LOADING");
}
export default fetch;
